'use strict'

process.chdir(__dirname)

const cdpc = require('../index')

const cm = new cdpc({
  loadInfoFile: '--mem',
  loadInfoType: 'json',
  debug: true,
  beforeStartCallback: (chk) => {
    chk.limit = {
      maxrss: 50_000
    }
  }
})

let app_cfg = {
  name : 'httpserver',
  file: 'app1.js',
  restart: 'always',
  restartDelay: 1000,
  options: {
    stdio: ['ignore', 1, 2, 'ipc']
  },
  limit: {
    maxrss: 60_000
  },
  monitorNetData: true,
  callback: (ch, cm, chk) => {
    ch.on('message', (msg) => {
      console.log('child get message', msg)
    })

    ch.on('exit', () => {
      console.log('cause:', chk.cause||'no errors')
    })

    ch.send({ pid: ch.pid})
  }
}

let app_cfg2 = {
  name : 'httpserver',
  file: 'app1.js',
  restart: 'always',
  restartDelay: 1000,
  args: [
    '--strong'
  ],
  options: {
    stdio: ['ignore', 1, 2, 'ipc']
  },
  limit: {
    maxrss: 60_000
  },
  monitorNetData: true,
  callback: (ch, cm, chk) => {
    ch.on('message', (msg) => {
      console.log('child get message', msg)
    })

    ch.on('exit', () => {
      console.log(chk.cause)
    })

    ch.send({
      pid: ch.pid,
      time: (new Date()).toLocaleString()
    })
  }
}

cm.run(app_cfg)

setTimeout(() => {
  cm.stop('httpserver', 500, () => {
    console.log('httpserver stoped')
  })
}, 2000)

setTimeout(() => {
  cm.start('httpserver')
  console.log('httpserver started')
}, 3500)


setTimeout(() => {
  console.log('即将使用新的配置加载应用...')
  cm.run(app_cfg2, true)
}, 3680)

setTimeout(() => {
  console.log(cm.appName)
  console.log('restart...')
  cm.restart('httpserver', 500)
}, 5000)

setTimeout(() => {
  console.log('pause...')
  cm.pause('httpserver')
}, 5500)

setTimeout(() => {
  console.log('stop...')
  cm.stop('httpserver')
}, 6600)

setTimeout(() => {
  console.log('start...')
  cm.start('httpserver')
}, 7500)

setTimeout(() => {
  console.log('测试完成，主进程退出。')
  cm.killAllChilds(process.pid, 'SIGKILL')
  process.exit(0)
}, 10000)

cm.dynamicStep = 5
cm.setStepSlice(20)
cm.setMaxStep(50, 105)

cm.monitorStart()
